package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApUserRealnameImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private IWemediaClient iWemediaClient; // 自媒体端feign客户端
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 分页条件查询用户审核列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getAuthList(AuthDto dto) {
        //1.入参检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页参数检查
        dto.checkParam();
        //3根据审核状态status进行查询
        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<ApUserRealname>();
        if (dto.getStatus() != null) {
            lqw.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        List<ApUserRealname> apUserRealnameList = list(lqw);

        //4.响应数据返回
        return ResponseResult.okResult(apUserRealnameList);
    }

    /**
     * 通过用户审核
     * 用户通过审核后需要开通自媒体账号（该账号的用户名和密码与app一致）
     *
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult authPass(AuthDto authDto) {
        //1.入参校验
        if (authDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据入参id查询用户认证信息表ap_user_realname中数据
        ApUserRealname apUserRealname = getById(authDto.getId());
        if (apUserRealname == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.根据user_id查询ap_user表中用户的数据,用于封装wmuser
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //.发送feign远程调用,为用户创建自媒体的的用户信息(wm_user)
        //先发送feign远程调用,尝试创建wm_user用户信息,如果创建失败了,那么就给出错误的提示给前端用户提示
        ResponseResult feignResponseResult = sendFeignToCreateWmUser(apUser);

        if (feignResponseResult.getCode().equals(200)) {
            //4.修改ap_user_realname表审核状态
            updateStatusAndReasonById(authDto.getId(), UserConstants.AUTH_PASS, "审核通过");
            //5.更新ap_user表中的字段数据
            apUser.setCertification(true);
            apUser.setIdentityAuthentication(true);
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        } else {
            return feignResponseResult;
        }
    }

    /**
     * feign远程调用自媒体端,保存一条自媒体用户信息
     *
     * @param apUser
     * @return
     */
    private ResponseResult sendFeignToCreateWmUser(ApUser apUser) {
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setCreatedTime(new Date());

        return iWemediaClient.saveWmUser(wmUser);
    }

    /**
     * 用户审核失败:更新状态即可
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AuthDto dto) {
        //1.入参校验
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        updateStatusAndReasonById(dto.getId(), UserConstants.AUTH_FAIL, dto.getMsg());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 操作数据库表ap_user_realname
     * 根据id 更新用户的状态 以及审核原因
     *
     * @param id     主键id
     * @param status 状态: 0创建中 1待审核 2审核失败 9审核通过
     * @param reason 审核原因
     * @return
     */
    private void updateStatusAndReasonById(Integer id, Short status, String reason) {
        //1.入参校验
        if (id == null || status == null) {
            return;
        }
        //2.根据id修改状态
        update(Wrappers.<ApUserRealname>lambdaUpdate()
                .eq(ApUserRealname::getId, id)
                .set(ApUserRealname::getStatus, status)
                .set(StringUtils.isNoneBlank(reason), ApUserRealname::getReason, reason)
                .set(ApUserRealname::getUpdatedTime, new Date()));
    }
}
